package config

import (
	"fmt"
	"log"
	"strings"

	"github.com/spf13/viper"
)

type Config struct {
	Server   ServerConfig   `mapstructure:"server"`
	Database DatabaseConfig `mapstructure:"database"`
	Redis    RedisConfig    `mapstructure:"redis"`
	JWT      JWTConfig      `mapstructure:"jwt"`
	Email    EmailConfig    `mapstructure:"email"`
	Upload   UploadConfig   `mapstructure:"upload"`
}

type ServerConfig struct {
	Port int    `mapstructure:"port"`
	Mode string `mapstructure:"mode"`
}

type DatabaseConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Username string `mapstructure:"username"`
	Password string `mapstructure:"password"`
	Name     string `mapstructure:"name"`
}

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

type JWTConfig struct {
	SecretKey         string `mapstructure:"secret_key"`
	ExpireTime        int    `mapstructure:"expire_time"`
	RefreshSecretKey  string `mapstructure:"refresh_secret_key"`
	RefreshExpireTime int    `mapstructure:"refresh_expire_time"`
	Issuer            string `mapstructure:"issuer"`
}

type EmailConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Username string `mapstructure:"username"`
	Password string `mapstructure:"password"`
}

type UploadConfig struct {
	UploadDir    string `mapstructure:"upload_dir"`
	StaticServer struct {
		Port int `mapstructure:"port"`
	} `mapstructure:"static_server"`
}

var AppConfig Config

func InitConfig(env string) {
	// 设置配置文件路径
	viper.AddConfigPath("./config")
	viper.AddConfigPath(".") // 当前目录

	// 根据环境选择配置文件
	switch env {
	case "production":
		viper.SetConfigName("production")
	case "test":
		viper.SetConfigName("test")
	default:
		viper.SetConfigName("development")
		env = "development"
	}

	// 设置配置文件类型
	viper.SetConfigType("yaml")

	// 读取环境变量
	viper.AutomaticEnv()
	viper.SetEnvPrefix("APP")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	// 监听配置文件变化
	viper.WatchConfig()

	// 可选：调试输出，确认 viper 能读到 key
	// fmt.Println("viper jwt.secret_key =", viper.GetString("jwt.secret_key"))

	// 解析配置到结构体
	if err := viper.Unmarshal(&AppConfig); err != nil {
		log.Fatalf("Unable to decode config into struct: %v", err)
	}

	fmt.Printf("Loaded %s configuration successfully\n", env)
}
